#include <esp_log.h>
#include <driver/i2c.h>
#include "memory"
#include "SensorManager.h"
#include "AdvertisementData.h"

extern "C" {
#include <string.h>
#include "nvs_flash.h"
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 1, 0))
#include "esp_netif.h"
#else
#include "tcpip_adapter.h"
#endif
}

#include "GattsService.h"
#include "EnvIIGattCharacteristic.h"
#include "GattsApplication.h"
#include "BleServer.h"
#include "EnvIIGattCharacteristicDesc.h"
#include "EnvIIServer.h"


static const char *TAG = "ENV-II-BT";

extern "C" {

static const uint8_t temptureValue[2]      = {0x16, 0x01}; //278 -> 27.8
static const uint8_t humidityValue[2]      = {0xAE, 0x15}; //5550 -> 55.5
static const uint8_t pressureValue[4]      = {0x02, 0x76, 0x0F, 0x00}; //1013250 -> 101325.0

void app_main(void) {
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 1, 0))
    ESP_ERROR_CHECK(esp_netif_init());
#else
    tcpip_adapter_init();
#endif
    BleServer::instance()->probe();
    try {
        auto bleApplication = std::make_shared<GattsApplication>(
            0,
            "EnvII");
        auto envServer = std::make_shared<EnviiServer>();

        bleApplication->addService(envServer);
        BleServer::instance()->setGattsApplication(bleApplication);
    }catch (const std::exception& e) {
        ESP_LOGE(TAG, "Caught exception: %s\n", e.what());
    }


//    auto humidity = std::make_shared<GattCharacteristic>(
//    );
//    auto pressure = std::make_shared<GattCharacteristic>(
//    );
//

    for(;;){
        sleep(3);
    }

} //app_main
} //extern "C"